/*
 Copyright (c) 2008, Desmond Elliott
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the
 documentation and/or other materials provided with the distribution.
 * Neither the name of Desmond Elliott nor the names of its contributors may
 be used to endorse or promote products derived from this software without
 specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY Desmond Elliott ``AS IS'' AND ANY
 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL Desmond Elliott BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "GuardianReader.h"
#import <Quartz/Quartz.h>

@interface GuardianReader (Private)
  -(void)loadPDF:(id)sender;
@end

@implementation GuardianReader

/**
 * When the application loads, create an autoreleased NSToolbar with the default
 * set of items and attach the toolbar to the window. Create a new thread to
 * retrieve and display the Top Stories.
 */
-(void)awakeFromNib
{
  [self createDictionaryOfToolbarItems];
  NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier:@"Guardian Reader Toolbar"] autorelease];
  [toolbar setDelegate:self];
  [toolbar setAllowsUserCustomization:YES];
  [window setToolbar:toolbar];
  NSArray *array = [NSArray arrayWithArray:[toolbar items]];
  [NSThread detachNewThreadSelector:@selector(retrievePDF:) toTarget:self withObject:[array objectAtIndex:0]];
  [window setDelegate:self];
}

-(void)dealloc
{
  [pdfView release];
  [window release];
  [toolbarItems release];
  [super dealloc];
}

/**
 * Each NSToolbarItem has an integer tag associated with it. Depending on the 
 * value of the tag of the item selected by the user, download the appropriate 
 * PDF and display the PDF.
 */
-(void)loadPDF:(id)sender
{
  [self clearPDFView];
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  NSURL *url;
  switch ([sender tag])
  {
    case 0:
      url = [NSURL URLWithString:@"http://download.guardian.co.uk/g24/Topstories.pdf"];
      break;
    case 1:
      url = [NSURL URLWithString:@"http://download.guardian.co.uk/g24/World.pdf"];
      break;
    case 2:
      url = [NSURL URLWithString:@"http://download.guardian.co.uk/g24/Media.pdf"];
      break;
    case 3:
      url = [NSURL URLWithString:@"http://download.guardian.co.uk/g24/Business.pdf"];    
      break;
    case 4:
      url = [NSURL URLWithString:@"http://download.guardian.co.uk/g24/Sport.pdf"];    
      break;
  }
  [pdfView setDocument:[[[PDFDocument alloc] initWithURL: url] autorelease]];
  [self verifyDocument:sender];
  [pool release]; 
}

/**
 * This method only exists to act as a way to have the application not block
 * while it is retrieving new content to display in the window.
 */
-(IBAction)retrievePDF:(id)sender
{
  NSMutableString *title = [NSMutableString stringWithString:@"Loading... "];
  [title appendString:[sender label]];
  [window setTitle:title];
  [NSThread detachNewThreadSelector:@selector(loadPDF:) toTarget:self withObject:sender]; 					
}

/**
 * Remove the reference count to the pdfView document and hide the pdfView.
 */
-(void)clearPDFView
{
  [pdfView setDocument:nil];
  [pdfView setHidden:YES];
}

/**
 * If the pdfView did not receive a document then show the (quite unhelpful)
 * error message.
 */
-(void)verifyDocument:(id)sender
{
  NSMutableString *title = [[NSMutableString alloc] init];	
  if ([pdfView document] == nil)
  { 
    [pdfView setHidden:YES];
    [title appendString:@"Failed to load "];
    [title appendString:[sender label]];
  }
  else
  {
    [pdfView setHidden:NO];
    [title appendString:@"Guardian Reader - "];
    [title appendString:[sender label]];
  }
  [window setTitle:title];  
}

/**
 * Required delegate.
 *
 * Return a new NSToolbarItem by creating a copy of a Toolbar item as created by
 * the addItemToDictionary:withIdentifier:withImage:withTag method.
 */
-(NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
  NSToolbarItem *newItem = [[[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier] autorelease];
  NSToolbarItem *item= [toolbarItems objectForKey:itemIdentifier];
  [newItem setLabel:[item label]];
  [newItem setPaletteLabel:[item paletteLabel]];
  [newItem setTag:[item tag]];
  [newItem setImage:[item image]];
  [newItem setAction:[item action]];
  [newItem setTarget:[item target]];
  return newItem;
}

/**
 * Required delegate.
 *
 * Declares the default NSToolbar configuration of Guardian Reader.
 */
-(NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar
{
  return [NSArray arrayWithObjects:@"Top Stories", @"World", @"Media", 
                                   @"Business", @"Sport", 
                                  NSToolbarSeparatorItemIdentifier, 
                                  NSToolbarPrintItemIdentifier, 
                                  NSToolbarFlexibleSpaceItemIdentifier, nil];
}

/**
 * Required delegate.
 *
 * Declares the allowed NSToolbarItems in Guardian Reader's NSToolbar.
 */
-(NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar
{
  return [NSArray arrayWithObjects:@"Top Stories", @"World", @"Media", 
                                   @"Business", @"Sport", 
                                  NSToolbarSeparatorItemIdentifier, 
                                  NSToolbarPrintItemIdentifier, 
                                  NSToolbarFlexibleSpaceItemIdentifier, nil];
}

/**
 * Create a reference NSToolbarItem for each custom NSToolbarItem.
 */
-(void)createDictionaryOfToolbarItems
{
  toolbarItems = [NSMutableDictionary dictionary];
  [self addItemToDictionary:toolbarItems withIdentifier:@"Top Stories" withImage:@"2179047732_0d2843bebb_s" withTag:0];
  [self addItemToDictionary:toolbarItems withIdentifier:@"World" withImage:@"514406103_72866daa16_s" withTag:1];
  [self addItemToDictionary:toolbarItems withIdentifier:@"Media" withImage:@"450642954_6cbce9d065_s" withTag:2];
  [self addItemToDictionary:toolbarItems withIdentifier:@"Business" withImage:@"56998544_e0aa8eb47a_s" withTag:3];
  [self addItemToDictionary:toolbarItems withIdentifier:@"Sport" withImage:@"105967616_8854365406_s" withTag:4];
}

/**
 * Creates a new NSToolbarItem and stores the item in a dictionary for retrieval.
 */
-(void)addItemToDictionary:(NSMutableDictionary*)dictionary withIdentifier:(NSString *)identifier withImage:(NSString *)image withTag:(int)tag
{
  NSToolbarItem *item = [[[NSToolbarItem alloc] initWithItemIdentifier:identifier] autorelease];
  [item setLabel:identifier];
  [item setPaletteLabel:identifier];
  [item setTag:tag];
  [item setImage:[NSImage imageNamed:image]];
  [item setAction:@selector(retrievePDF:)];
  [item setTarget:self];
  [dictionary setObject:item forKey:identifier];
}

/**
 * Delegate.
 *
 * Overriding this delegate means the application will terminate when the user
 * closes the window.
 */
- (void)windowWillClose:(NSNotification *)notification
{
  [[NSApplication sharedApplication] terminate:self];
}  
@end